package com.huishi;

import com.huishi.ui.FileChooserUI;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.metrics.buffering.BufferingApplicationStartup;
import org.yaml.snakeyaml.Yaml;

import javax.swing.*;
import java.io.IOException;
import java.io.InputStream;
import java.net.BindException;
import java.net.ServerSocket;
import java.util.Map;

@SpringBootApplication
@MapperScan("com.huishi.mapper")
@Slf4j
public class Main implements CommandLineRunner {
    @Autowired
    FileChooserUI fileChooserUI;

    public static void main(String[] args) {
        int port = getPort(args);
        if (!isPortAvailable(port)) {
            JOptionPane.showMessageDialog(null, "端口 " + port + " 已被占用，程序已经在运行！", "错误", JOptionPane.ERROR_MESSAGE);
            System.exit(0);
        }

        // 开启图形化界面
        System.setProperty("java.awt.headless", "false");
        // 启动 Spring 应用
        try {
            SpringApplication.run(Main.class, args);
        } catch (Exception e) {
            log.error("程序启动报错：",e);
            System.exit(1);
        }

    }

    private static boolean isPortAvailable(int port) {
        try (ServerSocket serverSocket = new ServerSocket(port)) {
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    private static int getPort(String[] args) {
        // 默认端口
        int defaultPort = 10000;

        // 从 YAML 配置文件获取端口号
        try (InputStream inputStream = Main.class.getClassLoader().getResourceAsStream("application.yml")) {
            if (inputStream != null) {
                Yaml yaml = new Yaml();
                Map<String, Object> config = yaml.load(inputStream);
                Map<String, Object> server = (Map<String, Object>) config.get("server");
                if (server != null && server.containsKey("port")) {
                    return Integer.parseInt(server.get("port").toString());
                }
            }
        } catch (Exception e) {
            System.err.println("无法读取配置文件，使用默认端口: " + defaultPort);
        }

        return defaultPort; // 返回默认端口
    }

    @Override
    public void run(String... args) {
        if (args.length > 0) {
            String urlParam = args[0];
            String userName = urlParam.substring(urlParam.lastIndexOf("=") + 1);
            fileChooserUI.userNameField.setText(userName);
            log.info("程序启动，URL 参数：{}", urlParam);
            log.info("设置用户名称为: {}", userName);
        } else {
            log.info("程序启动，没有 URL 参数");
        }
    }
}